package com.zw.hrm.handler;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.zw.hrm.constants.MQConstants;
import com.zw.hrm.feignclients.FastdfsFeignClient;
import com.zw.hrm.util.MyFileUtils;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@Component
public class PageStaticHandler {
    @Autowired
    private FastdfsFeignClient fastdfsFeignClient;

    @RabbitListener(queues = {MQConstants.NAME_QUEUE_PAGE_DIRECT})
    public void recvEmail(String msg, Message message, Channel channel) throws IOException {
        //解析消息，还原成map
        Map<String,String> map = JSON.parseObject(msg ,Map.class );
        //html在fastdfs下载路径
        String htmlPathInFastdfs = map.get("htmlPathInFastdfs");
        // nginx物理路径
        String physicalPath = map.get("physicalPath");

        //下载html到nginx
        byte[] htmlBytes = fastdfsFeignClient.download(htmlPathInFastdfs);
        if (htmlBytes == null || htmlBytes.length <= 0){
            throw new RuntimeException("从fastdfs下载html失败");
        }
        File file = MyFileUtils.createFile(physicalPath);
        FileCopyUtils.copy(htmlBytes, file);

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }

}